package com.unf.edu.rms.service;

import java.util.List;
import java.util.LinkedList;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.unf.edu.rms.dao.Category;
import com.unf.edu.rms.dao.Faculty;

@Service
public class CategoryService {
	
	@Autowired
	private SessionFactory sessionFactory;
	
	@Transactional
	public List<Category> viewCategoryTable()
	{
		System.out.println("ThesisService.viewCategoryTable()");
		Session session = sessionFactory.getCurrentSession();
		String hql = "FROM Category";
		Query query = session.createQuery(hql);
		List <Category> categoryList = query.list();
		List <Category> sortedCatList = new LinkedList<Category>();
		List <Category> tempList = new LinkedList <Category> ();
		Category node = null;
		for(int i = 0; i < categoryList.size(); i++){
			Category category = (Category) categoryList.get(i);
			if(category.getCategoryName().equals("No Category Provided")){
				node = category;
			}
			else if(sortedCatList.size()==0){
				sortedCatList.add(category);
			}
			else {
			boolean sorted = false;
				for(int j = 0; j < sortedCatList.size(); j++){
					int value = category.getCategoryName().compareTo(sortedCatList.get(j).getCategoryName());
					System.out.println("1: " + category.getCategoryName() + "   2: " + sortedCatList.get(j).getCategoryName() + "  v: " + value + "  i:" + i + "  j:"+j);
					if(value < 0 && sorted == false){
						sortedCatList.add(j, category);
						sorted = true;
					}
					if(j == sortedCatList.size()-1 && sorted==false){
						sortedCatList.add(j+1, category);
						sorted = true;
					}
				}
			}
		}
		sortedCatList.add(0, node);
		for(Category category:sortedCatList){
			System.out.println("Sorted Category List:  " + category.getCategoryName());
		}
		return sortedCatList;
	}
	
	@Transactional
	public void addNewCategory(Category category)
	{
		Session session = sessionFactory.getCurrentSession();
		session.save(category);
		
	}
	
	@Transactional
	public Category getCategoryById(int categoryId)
	{
		Session session = sessionFactory.getCurrentSession();
		String hql = "FROM Category where categoryId=:categoryId";
		Query query = session.createQuery(hql);
		query.setInteger("categoryId", categoryId);
		Category category = (Category)query.list().get(0);
		return category;
	}
	
	
	@Transactional
	public void updateCategory(Category category)
	{
		Session session = sessionFactory.getCurrentSession();
		String hql = "FROM Category where categoryId=:categoryId";
		Query query = session.createQuery(hql);
		query.setInteger("categoryId", category.getCategoryId());
		session.update(category);
	}
}
